package com.easyclearance.baseutil;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.apache.commons.codec.binary.Base64;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.stereotype.Repository;

/*******************************************************************************
 * ImgUtil 图片处理工具包
 *
 * @author Sunshine
 * @ClassName: ImgUtil
 * @Description: TODO
 * @author travbao@163.com
 * @date 06, 13, 2019 9:28:28 AM
 */
@Repository
public class ImgUtil {
	
	@Resource
	UploadImg uploadImg;
	@Resource
	ByteByUrl byteByUrl;

	/**
	 * pdf文件转图片
	 * @param filePath
	 * @param timestamp
	 * @return
	 */
	public List<String> pdfToImagePath(String filePath,String timestamp) {
		List<String> list = new ArrayList<>();
		String fileDirectory = filePath.substring(0, filePath.lastIndexOf("."));// 获取去除后缀的文件路径

		String imagePath;
		File file = new File(filePath);
		try {
			File f = new File(fileDirectory);
			if (!f.exists()) {
				f.mkdir();
			}
			PDDocument doc = PDDocument.load(file);
			PDFRenderer renderer = new PDFRenderer(doc);
			int pageCount = doc.getNumberOfPages();
			for (int i = 0; i < pageCount; i++) {
				// 方式1,第二个参数是设置缩放比(即像素)
				// BufferedImage image = renderer.renderImageWithDPI(i, 296);
				// 方式2,第二个参数是设置缩放比(即像素)
				BufferedImage image = renderer.renderImage(i, 2.5f); // 第二个参数越大生成图片分辨率越高，转换时间也就越长
				imagePath = fileDirectory + "/" + timestamp + i + ".jpg";
				ImageIO.write(image, "PNG", new File(imagePath));
				list.add(imagePath);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}

	// ///////////判断图片是彩色图片还是黑白图片/////////////////
	/**
	 *
	 * @param imagePath
	 *            下载图片的路径
	 * @return 返回true是彩色图片 返回false是黑灰图片
	 * @throws Exception
	 */
	public Boolean execote(String imagePath)  {
		boolean color = false;

		try {
			//转换字节流
			InputStream inputStream = new URL(imagePath).openConnection().getInputStream();
			//读取
			BufferedImage src = ImageIO.read(inputStream);
			int height = src.getHeight();
			int width = src.getWidth();
			int[] rgb = new int[4];
			int o = 0;
			for (int i = 0; i < width; i++) {
				for (int j = 0; j < height; j++) {
					int pixel = src.getRGB(i, j);
					rgb[1] = (pixel & 0xff0000) >> 16;
					rgb[2] = (pixel & 0xff00) >> 8;
					rgb[3] = (pixel & 0xff);
					// 如果像素点不相等的数量超过50个 就判断为彩色图片
					if (rgb[1] != rgb[2] && rgb[2] != rgb[3] && rgb[3] != rgb[1]) {
						o += 1;
						if (o >= 50) {
							color = true;
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			color = true;
		}
		return color;
	}

	/**
	 * 获取在线文件的base64
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public String encodeImageToBase64(URL url) throws Exception {
		//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		System.out.println("图片的路径为:" + url.toString());
		//打开链接
		HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection) url.openConnection();
			//设置请求方式为"GET"
			conn.setRequestMethod("GET");
			//超时响应时间为5秒
			conn.setConnectTimeout(5 * 1000);
			//通过输入流获取图片数据
			InputStream inStream = conn.getInputStream();
			//得到图片的二进制数据，以二进制封装得到数据，具有通用性
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			//创建一个Buffer字符串
			byte[] buffer = new byte[1024];
			//每次读取的字符串长度，如果为-1，代表全部读取完毕
			int len = 0;
			//使用一个输入流从buffer里把数据读取出来
			while ((len = inStream.read(buffer)) != -1) {
				//用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
				outStream.write(buffer, 0, len);
			}
			//关闭输入流
			inStream.close();
			byte[] data = outStream.toByteArray();
			//对字节数组Base64编码
			String base64 = Base64.encodeBase64String(data);
			System.out.println("网络文件[{}]编码成base64字符串:[{}]"+url.toString()+base64);
			return base64;//返回Base64编码过的字节数组字符串
		} catch (IOException e) {
			e.printStackTrace();
			throw new Exception("图片上传失败,请联系客服!");
		}
	}
	
	
	public String writeImage(String name,String passport,String nationality,String birth,String sex,String passportExpiry,String email,String mobile,String arrDate,String arrModel
			,String depDate,String embarkation,String Transportation,String stayAcc,String addressMalaysia,String postCode,String city,String state,String pin,String filename) {
		String imgUrlString = ""; 
		try {
	            // 加载原始图像文件
			String fileString = "";
			if (addressMalaysia.length()>50) {
				fileString = "/usr/local/Imgfile/MALE.JPEG";
//				fileString = "/Users/slunshine/Downloads/lla/WechatIMG352.jpg";
			}else {
				fileString = "/usr/local/Imgfile/MAL.JPEG";
//				fileString = "/Users/slunshine/Downloads/lla/WechatIMG354.jpg";
			}
				File input = new File(fileString);
//	            File input = new File("/usr/local/Imgfile/MAL.JPEG");
	            BufferedImage image = ImageIO.read(input);
	            
	            // 获取图像的Graphics2D对象
	            Graphics2D g2d = (Graphics2D) image.getGraphics();
	            
	            // 设置画笔颜色为红色
	            g2d.setColor(Color.BLACK);
	            
	            String time = new SimpleDateFormat("yyyy/M/d HH:mm").format(new Date());
	            Font font0 = new Font("思源黑体", Font.PLAIN, 16);
	            g2d.setFont(font0);
	            g2d.drawString(time, 50, 45);
	            
	            
	            // 在图像上添加文本
	            Font font = new Font("思源黑体", Font.PLAIN, 25);
	            g2d.setFont(font);
	            int x = 397;
	            int y = 533;
	            g2d.drawString(name, x, y);
	            
	            
	            int y1 = 355 + 215;
	            g2d.drawString(passport, x, y1);
	            
	            int y2 = 411 + 215;
	            g2d.drawString(nationality, x, y2);
	            
	            int y3 = 467 + 215;
	            g2d.drawString(birth, x, y3);
	            
	            int y4 = 504 + 215;
	            g2d.drawString(sex, x, y4);
	            
	            int y5 = 543 + 215;
	            g2d.drawString(passportExpiry, x, y5);
	            
	            int y6 = 585 + 215;
	            g2d.drawString(email, x, y6);
	            
	            int y7 = 623 + 215;
	            g2d.drawString(mobile, x, y7);
	            
	            int y8 = 700 + 215;
	            g2d.drawString(arrDate, x, y8);
	            
	            int y9 = 740 + 215;
	            g2d.drawString(arrModel, x, y9);
	            
	            int y10 = 780 + 215;
	            g2d.drawString(depDate, x, y10);
	            
	            int y11 = 837 + 215;
	            g2d.drawString(embarkation, x, y11);
	            
	            int y12 = 890 + 215;
	            g2d.drawString(stayAcc, x, y12);
	            
	            int y12_0 = 930 + 215;
	            g2d.drawString(Transportation, x, y12_0);
	            
	            int y13 = 970 + 215;
	            int y13_0 = 1005 + 215;
	            if (addressMalaysia.length()>50) {
	            	g2d.drawString(addressMalaysia.substring(0, 50), x, y13);
	            	g2d.drawString(addressMalaysia.substring(50), x, y13_0);
				}else {
		            g2d.drawString(addressMalaysia, x, y13);
				}
	            
	            int y14 = 1020 + 215;
	            if (addressMalaysia.length()>50) {
					y14 = y14 + 25;
				}
	            g2d.drawString(postCode, x, y14);
	            
	            int y15 = 1055 + 215;
	            if (addressMalaysia.length()>50) {
	            	y15 = y15 + 25;
				}
	            g2d.drawString(city, x, y15);
	            
	            int y16 = 1095 + 215;
	            if (addressMalaysia.length()>50) {
	            	y16 = y16 + 25;
				}
	            g2d.drawString(state, x, y16);
	            
	            
	            Font font1 = new Font("思源黑体", Font.ROMAN_BASELINE, 40);
	            g2d.setFont(font1);
	            int y17 = 1190 + 215;
	            g2d.drawString(pin, x, y17);
	            
	            
	            
//	            String str = "https://wx.mail.qq.com/home/index?sid=zdJRU4xxSXgu0XdPAGAwYQAA#/read/ZL0006_6znNuciMPewuBWUA7W97Ue2";
//	            Font font10 = new Font("黑体", Font.PLAIN, 16);
//	            g2d.setFont(font10);
//	            g2d.drawString(str, 50, 1665);
//	            String filepathString = "/Users/slunshine/Downloads/lla/"+filename;
	            String filepathString = "/usr/local/Imgfile/"+filename;
	            // 保存修改后的图像到新文件
	            File output = new File(filepathString);
	            ImageIO.write(image, "jpeg", output);
	            
                //图片转换base64
                String getImageStr = byteByUrl.GetImageStr(new FileInputStream(output));
                //图片上传七牛云
				try {
					String putBase64image = new UploadImg().putBase64image(getImageStr, filename);
	                //图片路径
	                imgUrlString = "https://cdn.travbao.com/" + putBase64image;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	            System.out.println("图像已成功编辑并保存！");
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
		return imgUrlString;
	}
	public void main(String[] args) {
		String ssString = "TESTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT";
		writeImage("NAMENAME", "TEST", "TEST", "TEST", "TEST", "TEST", "TEST", "TEST", "TEST", "TEST", "TEST", "TEST", "TEST", "TEST111", ssString, "TEST", "TEST", "TEST", "TEST", "TEST.JPEG");
		
		System.out.println(ssString.length());

//		List<String> pdfToImagePath = pdfToImagePath(urlstr, "15253715987");
//		System.out.println(pdfToImagePath);
	}
}
